from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer
from django.conf import settings

from areas.models import Area
from utils.models import BaseModel


# Create your models here.


class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")
    email_active = models.BooleanField(default=False, verbose_name='邮箱激活')
    default_address = models.ForeignKey('Address', on_delete=models.SET_NULL,
                                        null=True, blank=True,
                                        related_name='users', verbose_name='默认地址')

    class Meta:
        db_table = 'tb_users'

    def __str__(self):
        return self.username

    def generate_verify_url(self):
        token = {'user_id': self.id, 'email': self.email}

        # 加密数据
        serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=300)
        token = serializer.dumps(token)

        # 拼接到url地址中
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s' % token.decode()

        return verify_url

    @classmethod
    def decode_token(cls, token):
        # 解密数据
        serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=300)
        try:
            dict_data = serializer.loads(token)
            user_id = dict_data['user_id']
            # user = self.objects.get(id=user_id)
            user = User.objects.get(id=user_id)
        except Exception as e:
            return None

        return user


class Address(BaseModel):
    user = models.ForeignKey(User, related_name='address',
                             verbose_name='用户', on_delete=models.CASCADE)

    title = models.CharField(verbose_name='详细地址', max_length=20)

    receiver = models.CharField(verbose_name='收货人', max_length=20)

    province = models.ForeignKey(Area, related_name='province',
                                 verbose_name='省', on_delete=models.PROTECT)

    city = models.ForeignKey(Area, on_delete=models.PROTECT,
                             related_name='city', verbose_name='市')

    district = models.ForeignKey(Area, on_delete=models.PROTECT,
                                 related_name='district', verbose_name='区')

    place = models.CharField(max_length=11, verbose_name='地址')

    mobile = models.CharField(max_length=11, verbose_name='手机号')

    tel = models.CharField(max_length=20, null=True, blank=True,
                           default='', verbose_name='固定电话')

    email = models.CharField(max_length=30, null=True, blank=True,
                             default='', verbose_name='电子邮箱')

    is_deleted = models.BooleanField(verbose_name='逻辑删除', default=False)

    class Meta:
        db_table = "tb_address"
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        ordering = ['-update_time']


